import { createFloatBox } from '../components/FloatBox';
import { MessageType } from '../types';

/**
 * Content Script for Chrome Extension
 * 运行在网页环境中，负责与页面交互、注入悬浮框等功能
 */
class ContentScript {
  private floatBox: any = null;
  private isFloatBoxVisible = false;
  private selectedText = '';
  private observer: MutationObserver | null = null;

  constructor() {
    this.init();
  }

  private init() {
    // 等待页面完全加载
    if (document.readyState === 'loading') {
      document.addEventListener('DOMContentLoaded', () => {
        this.setupContentScript();
      });
    } else {
      this.setupContentScript();
    }
  }

  private setupContentScript() {
    // 设置消息监听器
    this.setupMessageListener();
    
    // 设置文本选择监听器
    this.setupTextSelectionListener();
    
    // 设置页面变化监听器
    this.setupPageObserver();
    
    // 设置快捷键监听器
    this.setupKeyboardShortcuts();
    
    // 自动显示悬浮球
    this.showFloatBox();
    
    console.log('Content script initialized on:', window.location.href);
  }

  /**
   * 设置消息监听器
   */
  private setupMessageListener() {
    chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
      this.handleMessage(message, sender, sendResponse);
      return true;
    });
  }

  /**
   * 处理来自背景脚本或其他组件的消息
   */
  private handleMessage(
    message: any,
    sender: chrome.runtime.MessageSender,
    sendResponse: (response?: any) => void
  ) {
    console.log('Content script: Received message:', message, 'from:', sender);
    try {
      switch (message.type) {
        case 'TOGGLE_FLOAT_BOX':
          console.log('Content script: Handling TOGGLE_FLOAT_BOX');
          this.toggleFloatBox();
          sendResponse({ success: true });
          break;

        case 'SHOW_FLOAT_BOX':
          console.log('Content script: Handling SHOW_FLOAT_BOX');
          this.showFloatBox(message.payload);
          sendResponse({ success: true });
          break;

        case 'HIDE_FLOAT_BOX':
          console.log('Content script: Handling HIDE_FLOAT_BOX');
          this.hideFloatBox();
          sendResponse({ success: true });
          break;

        case 'GET_PAGE_INFO':
          console.log('Content script: Handling GET_PAGE_INFO');
          const pageInfo = this.getPageInfo();
          sendResponse({ success: true, data: pageInfo });
          break;

        case 'GET_SELECTED_TEXT':
          console.log('Content script: Handling GET_SELECTED_TEXT');
          sendResponse({ success: true, data: this.selectedText });
          break;

        default:
          console.log('Content script: Unknown message type:', message.type);
          sendResponse({ success: false, error: 'Unknown message type' });
      }
    } catch (error) {
      console.error('Error handling message in content script:', error);
      sendResponse({ success: false, error: (error as Error).message });
    }
  }

  /**
   * 设置文本选择监听器
   */
  private setupTextSelectionListener() {
    // 监听文本选择变化
    document.addEventListener('selectionchange', () => {
      const selection = window.getSelection();
      const text = selection?.toString().trim();
      
      if (text && text.length > 0) {
        this.selectedText = text;
        
        // 发送选中文本到背景脚本
        chrome.runtime.sendMessage({
          type: 'TEXT_SELECTED',
          payload: {
            text: text,
            url: window.location.href,
            timestamp: Date.now()
          }
        }).catch(() => {
          // 忽略消息发送失败
        });
      }
    });
  }

  /**
   * 设置页面变化监听器
   */
  private setupPageObserver() {
    // 监听页面 DOM 变化
    this.observer = new MutationObserver((mutations) => {
      mutations.forEach((mutation) => {
        if (mutation.type === 'childList') {
          // 页面内容发生变化时的处理
          this.handlePageChange();
        }
      });
    });

    this.observer.observe(document.body, {
      childList: true,
      subtree: true
    });
  }

  /**
   * 处理页面变化
   */
  private handlePageChange() {
    // 可以在这里添加页面分析、内容检测等功能
    // 例如：检测特定元素、分析页面结构等
  }

  /**
   * 设置键盘快捷键
   */
  private setupKeyboardShortcuts() {
    document.addEventListener('keydown', (e) => {
      // Ctrl/Cmd + Shift + F: 切换悬浮框
      if ((e.ctrlKey || e.metaKey) && e.shiftKey && e.key === 'F') {
        e.preventDefault();
        this.toggleFloatBox();
      }

      // Ctrl/Cmd + Shift + T: 翻译选中文本
      if ((e.ctrlKey || e.metaKey) && e.shiftKey && e.key === 'T') {
        e.preventDefault();
        const selection = window.getSelection();
        const text = selection?.toString().trim();
        if (text) {
          this.showFloatBox({
            tool: 'translate',
            text: text
          });
        }
      }

      // ESC: 隐藏悬浮框
      if (e.key === 'Escape' && this.isFloatBoxVisible) {
        e.preventDefault();
        this.hideFloatBox();
      }
    });
  }

  /**
   * 切换悬浮框显示状态
   */
  private toggleFloatBox() {
    if (this.isFloatBoxVisible) {
      this.hideFloatBox();
    } else {
      this.showFloatBox();
    }
  }

  /**
   * 显示悬浮框
   */
  private showFloatBox(config?: any) {
    if (this.floatBox) {
      this.hideFloatBox();
    }

    try {
      this.floatBox = createFloatBox(config);
      this.isFloatBoxVisible = true;
      
      // 通知背景脚本悬浮框已显示
      chrome.runtime.sendMessage({
        type: 'FLOAT_BOX_SHOWN',
        payload: { url: window.location.href }
      }).catch(() => {
        // 忽略消息发送失败
      });
    } catch (error) {
      console.error('Failed to show float box:', error);
    }
  }

  /**
   * 隐藏悬浮框
   */
  private hideFloatBox() {
    if (this.floatBox) {
      this.floatBox.destroy();
      this.floatBox = null;
      this.isFloatBoxVisible = false;
      
      // 通知背景脚本悬浮框已隐藏
      chrome.runtime.sendMessage({
        type: 'FLOAT_BOX_HIDDEN',
        payload: { url: window.location.href }
      }).catch(() => {
        // 忽略消息发送失败
      });
    }
  }

  /**
   * 获取页面信息
   */
  private getPageInfo() {
    return {
      url: window.location.href,
      title: document.title,
      domain: window.location.hostname,
      pathname: window.location.pathname,
      timestamp: Date.now(),
      selectedText: this.selectedText,
      language: document.documentElement.lang || 'unknown'
    };
  }

  /**
   * 清理资源
   */
  public cleanup() {
    if (this.observer) {
      this.observer.disconnect();
    }
    
    if (this.floatBox) {
      this.hideFloatBox();
    }
  }
}

// 初始化内容脚本
const contentScript = new ContentScript();

// 页面卸载时清理资源
window.addEventListener('beforeunload', () => {
  contentScript.cleanup();
});

// 导出实例（如果需要在其他地方使用）
export default contentScript;